package project.ekko.listener.processor;

import com.github.kwhat.jnativehook.keyboard.NativeKeyEvent;
import project.ekko.listener.KeyEvent;
import project.ekko.wow.Fisher;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.LockSupport;
import java.util.function.Consumer;
import java.util.function.Predicate;
import java.util.logging.Level;
import java.util.logging.Logger;

public class FishProcessor implements Consumer<KeyEvent> {

    private long lastALTPressedTimestamp = -2000;

    private final Predicate<Void> predicate;

    private boolean autoFishActive = false;

    public FishProcessor() {
        Logger.getGlobal().info("Press key alt + 1 to reel and cast!");
        predicate = null;
    }

    public FishProcessor(Predicate<Void> predicate) {
        Logger.getGlobal().info("Press key alt + 1 to reel and cast!");
        this.predicate = predicate;
    }

    @Override
    public void accept(KeyEvent event) {
        switch (event.keyCode()) {
            case NativeKeyEvent.VC_ALT:
                lastALTPressedTimestamp = event.timestamp();
                break;
            case NativeKeyEvent.VC_1:
                if (event.timestamp() - lastALTPressedTimestamp > 1000) {
                    return;
                }
                lastALTPressedTimestamp = -2000;
                doFish();
                break;
            case NativeKeyEvent.VC_2:
                if (event.timestamp() - lastALTPressedTimestamp > 1000) {
                    return;
                }
                Logger.getGlobal().info("Auto-fishing is not yet supported, so please look forward to future versions!");


        }
    }

    private void doFish() {
        if (autoFishActive) {
            return;
        }
        Fisher.gotoFish();
    }

    private void startAutoFish() {
        if (autoFishActive) {
            return;
        }
        autoFishActive = true;
        var thread = new Thread(() -> {
            Fisher.gotoFish();
            while (true) {
                try {
                    if (!predicate.test(null)) {
                        LockSupport.parkNanos(TimeUnit.MILLISECONDS.toNanos(2000));
                    }
                } catch (Exception ex) {
                    Logger.getGlobal().log(Level.SEVERE, "sad! what's happen?", ex);
                }
                Fisher.gotoFish();
            }
        });
        thread.setName("auto-fish");
        thread.start();
    }

}
